package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * 数据库连接获取和释放工具类
 *
 * @公司 青软实训
 * @作者 fengjj
 */
public class DBUtil {

    static final String DB_URL = "jdbc:mysql://localhost:3360/itoffer?useUnicode=true&characterEncoding=utf8";
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "docker";

    private Connection conn = null;

    static {
        try {
            // 1.加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获得数据库的连接
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Connection conn = DBUtil.getConnection();
        System.out.println("获取的Connection：" + conn);
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeJDBC(ResultSet rs, Statement stmt, Connection conn) {
        //
        if (rs != null) {
            try {
                System.out.println("(rs) close conn:" + conn);
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                System.out.println("(stmt) close conn:" + conn);
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                System.out.println("(conn) close conn:" + conn);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}